<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Directions service</title>
    <script>
        sessionStorage.removeItem('routerWayPoints');   //每次打开页面都清除上一次剔除的站点缓存
        var CONFIG ={
            updateRouterUrl:"{{:url('/tms/UpdateRouter')}}",
            updateRouterDriver:"{{:url('/tms/UpdateRouterDriver')}}",
            getRouterUrl:"{{:url('/tms/GetRouters')}}",
            allRoutersUrl:"{{:url('/tms/router')}}",
            routerStrokeColor:['#00AFE4','#f20','#388bff','#1f1e1e','#000','#0c08ab','#1d3e1d','#003f59','#3ca009','#298fca','#FF9900','#FF9933','#993333','#003366','#003366','#FFFFCC','#FFFFCC','#00AFE4','#f20','#388bff','#1f1e1e','#000','#0c08ab','#1d3e1d'],
            doRecord:[],                         //操作记录
            currentOpearateRouterId:null,         //当前操作的路由id
            showOrHideSatues:"show",                //隐藏or显示状态 （show,hide）
            zoom:10,
            latAndLngPrecision:4,                    //经纬度精确到几位小数
            checkUnAssignTimeInterval:1000,          //定时检查有没有未分配的站点时间间隔
            updateRouterPointsTimeInterval:1000,     //定时更新Router详情模板内容的站点时间间隔
            delayPointsCounter:0,                   //到达客户地址超时记录数
            keydownAddRouterBtn:false,               //是否按下添加路由按钮
            drawingRouterEdgePoints:[]  ,     //添加多边形的四个顶点
            assignRouterTimer:null,           //分配站点到区域定时器
            updateRouterTimer:null,           //更新路线数据到服务器定时器
           // updateRouterTemplateIntervale:null,   //更新每条Router定时器
            driverPositionShowStatus:"false",
            addRouterNameTempValue:null,            //添加Router临时存放Route名字
            optimizeOrderpoints:[]    ,                 //路线站点顺序是否优化配置,手动初始化为ture，从历史记录恢复为false 如果值为true的话 则对路线站点按照收货时间排序
            wareHouseCenter:null,
            wareHouseCode:"{{$Think.get.wareHouse}}",
            territoryName:null ,                       //当前territory名字
        }
        var OBJECT = {
            directionsDisplay:[],   //路线图对象容器
            bermudaTriangle  : [],   //背景区域对象容器
            markers:[],               //标记聚类对象容器
            markerCluster:[] ,      //标记聚类对象句柄容器
            routersBgColorMap:[] ,  //路线对应的颜色 [routerId=>color]
            routersNameMap:[] ,  //路线对应的颜色 [routerId=>NAME]
            filterMarker:[],        //筛选出来的标记对象容器
            routerPonits:[],          //每条路线的地点 {points:每个地点,vehicleId：vehicleId，driver:driver,schedule:每条路线之间的点距离和时间,UpdateStatus:true or false}
            driverList :[],          //司机列表
            driverMarketList :[],          //司机标记对象容器
            CustomerList :[],          //客户标记对象容器 存放所有的客户信息
            vehicleList:[] ,               //车辆列表
            routerEdgePoints:[] ,          //每个router多边形的顶点
            customerPositionList:[],       //每个客户的信息
            dispalyPositonList:[],        //每个多边形的标记容器
            numberMarkerOnRouter:[],       //Router上每个数字Market (ABCD....=>1234....)
            exceptionRouter:new Set(),      //每个Router异常信息 （配送超时，超过上班最大时间,超出磅数）
            requestRoutePromiseHandle:[] ,               //Promise 对象容器
            requestRouteStatus:new Map()  ,             //请求Route状态    [routerId=>status( success or pending)]
            infowindow:[]
        };


    </script>
    <style>
        .labels {
            color: white;
            background-color: red;
            font-family: "Lucida Grande", "Arial", sans-serif;
            font-size: 10px;
            text-align: center;
            width: 30px;
            white-space: nowrap;
        }
    </style>
    <script  src="__STATIC__/static/js/jquery.js"></script>
    <script  src="__STATIC__/static/js/common.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-md5/2.10.0/js/md5.min.js"></script>
    <link rel="stylesheet" href="__STATIC__/static/css/router.css?v={{:config('STATIC_VERSION')}}">
    <link rel="stylesheet" href="__STATIC__/static/css/jq-tab.css?v={{:config('STATIC_VERSION')}}">
    <link rel="stylesheet" href="__STATIC__/static/css/tableStyle.css?v={{:config('STATIC_VERSION')}}">
    <link rel="stylesheet" href="__STATIC__/static/css/loading.css?v={{:config('STATIC_VERSION')}}">
    <script  src="__STATIC__/static/js/Polygon.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/RecordAndRestore.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/Router.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/Marker.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/jq-tab.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/handlebars-v4.0.11.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/Territory.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/getEdgePoints.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/Session.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/assignRoute.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/Server.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/Driver.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/assignDriver.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/Customer.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/alert.js?v={{:config('STATIC_VERSION')}}"></script>

    <script  src="__STATIC__/static/js/RecoveryFromRouteHistory.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/Hook.js?v={{:config('STATIC_VERSION')}}"></script>




    <!--函数区域-->
    <script type="text/javascript">
        showLoading();
        //获取路线时间和路程之后执行函数
        Hook.getInstance().addAction('afterCompleteRouteSchedule',Server.getInstance().updateRouters())
    </script>
    <script>

        var map;

        var RecordAndRestoreObj = new RecordAndRestore();
        var MarkerObj = new Marker();
        //  mapDraw.clear();    //清除cookie
        function objToArray(data) {
            let ret = [];
            for(var i=0;i<data.length;i++){
                let o={};
                for(let key in data[i]){
                    o[key] = data[i][key]
                }
                ret.push(o)
            }
            for(let i=0;i<ret.length;i++ ) {
                ret[i].lat = Number(ret[i].lat);
                ret[i].lng = Number(ret[i].lng);
            }
            return ret;
        }
        function getRoutetsAndShow() {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "{{:url('/tms/router')}}" ,
                data: {},
                success: function (result) {
                    $.each(result.body,function (key,value) {
                        routers = objToArray( value.routers );

                            Polygon.draw(routers,map ,value.id,key);
                            Router.getInstance().calculateAndDisplayRoute(routers,value.id,key);
                    })
                },
                error : function() {}
            });
        }
        /**
         * 获取车数据列表
         */
        function getVehicleList(){
            $.ajax({
                type: "POST",
                dataType: "json",
                url: '{{:url("/vehicle/index")}}' ,
                data: {},
                success: function (result) {
                    OBJECT.vehicleList = result.msg.data;

                },
                error : function() {
                    alert('获取信息失败')
                }
            });
        }
        /**
         * 获取Route列表
         */
        function getRouters(){
            $.ajax({
                type: "POST",
                dataType: "json",
                url: '{{:url("/tms/router")}}' ,
                data: {warehouse:CONFIG.wareHouseCode},
                success: function (result) {

                    RecoveryFromRouteHistory.getInstance().render( result.body );
                },
                error : function() {
                    alert('获取信息失败')
                }
            });
        }
        /**
         * 获取车数据列表
         */
        function getWareHouse(resolve){
            $.ajax({
                type: "POST",
                dataType: "json",
                url: '{{:url("/warehouse/get")}}' ,
                data: {warehouse:CONFIG.wareHouseCode},
                success: function (result) {
                    CONFIG.wareHouseCenter = result.msg;
                    resolve('SUCCESS');
                },
                error : function() {
                    alert('获取信息失败')
                }
            });
        }
        /**
         * 获取司机列表
         */
        function getDriverList( resolve= null){
            $.ajax({
                type: "POST",
                dataType: "json",
                url: '{{:url("/driver/warehouse/itmes")}}' ,
                data: {warehouse:CONFIG.wareHouseCode},
                success: function (result) {
                    OBJECT.driverList = result.msg.data;
                    Driver.getInstance().render(OBJECT.driverList);
                    resolve && resolve('SUCESS');
                },
                error : function() {
                    alert('获取信息失败')
                }
            });
        }
        /**
         * 获取订单列表
         */
        function getOrderList(){
            $.ajax({
                type: "POST",
                dataType: "json",
                url: '{{:url("/order/all")}}' ,
                data: {wareHouse:CONFIG.wareHouseCode},
                success: function (result) {

                    OBJECT.customerPositionList = objToArray(result.msg);
                    Customer.getInstance().render(OBJECT.customerPositionList);
                    Server.getInstance().assignPointToPolygon();
                },
                error : function() {
                    alert('获取信息失败');
                }
            });
        }

        function initMap() {
            showLoading();
            new Promise(function (resolve, reject) {
                getWareHouse(resolve);
            }).then(function(value){
                map = new google.maps.Map(document.getElementById('map'), {
                    zoom: CONFIG.zoom,
                    center: {lat: Number(CONFIG.wareHouseCenter.lat), lng:Number(CONFIG.wareHouseCenter.lng)},
                    mapTypeId: 'roadmap'
                });
                google.maps.event.addDomListener(map, 'zoom_changed', function() {
                    CONFIG.zoom = map.getZoom();
                });
                google.maps.event.addListener(map, "click", function (e) {
                    if(CONFIG.keydownAddRouterBtn)  //如果按下了添加Roter 按钮
                    {

                        let lat = (e.latLng.lat()).toFixed(5);
                        let lng = (e.latLng.lng()).toFixed(5);
                        CONFIG.drawingRouterEdgePoints.push({lat:Number(lat),lng:Number(lng)})
                    }
                    let len = CONFIG.drawingRouterEdgePoints.length;
                    if( len ==  4)
                    {
                        showLoading();
                        let routerId = md5(Math.random());
                        CONFIG.optimizeOrderpoints[routerId] = true;
                        OBJECT.routersBgColorMap[routerId] = CONFIG.routerStrokeColor.pop();
                        Polygon.draw(CONFIG.drawingRouterEdgePoints , map , routerId );
                        Polygon.setEdgePoints( routerId , CONFIG.drawingRouterEdgePoints );
                        OBJECT.routersNameMap[routerId] = CONFIG.addRouterNameTempValue;
                        CONFIG.keydownAddRouterBtn = false;
                        CONFIG.drawingRouterEdgePoints=[];
                        Server.getInstance().assignPointToPolygon();
                    }
                });
                getOrderList();

                const loadDriverAndVehicle = new Promise(function(resolve, reject) {
                    getDriverList();
                    getVehicleList();

                    setTimeout(()=>{
                        resolve('SUCCESS');
                    },2000)
                });
                loadDriverAndVehicle.then(function (status) {
                    getRouters();
                    Server.getInstance().requestRouter();
                    closeLayerMsg();
                })
            });

        }
    </script>
</head>
<body>
<!--loading 按钮-->
<div class="mask"></div>
<div class="loader">
    <div class="square" ></div>
    <div class="square"></div>
    <div class="square last"></div>
    <div class="square clear"></div>
    <div class="square"></div>
    <div class="square last"></div>
    <div class="square clear"></div>
    <div class="square "></div>
    <div class="square last"></div>
</div>
<!--loading 按钮-->
<div class="header">
    <div class="logo"></div>
    <div class="info">
         <span>返回</span>
        <span>3562.23</span>
        <span>jack.l</span>
    </div>
</div>
<div class="nav-title">
    <div class="tab-text">
        Route
    </div>

    <div class="info">
        <?php echo date('Y-m-d');?> Maywood
    </div>
    <script></script>
    <div class="right">
        <span onclick="RecordAndRestoreObj.restore()" style="display: none;">撤回</span>
    </div>
</div>
<div class="work-area">
    <div class="open-show-btn open"></div>
    <div class="menus ">
        <ul>
            <li class="active"><span>Customers</span></li>
            <li onclick="showDriverList()"><span>Drivers</span></li>
            <li onclick="renderVehicleList()"><span>Vehicles</span></li>
            <li><span>Depost</span></li>
            <li onclick="assignRoute.getInstance().render()"><span>Routes</span></li>
            <li><span>Notes</span></li>
        </ul>
        <div class="clear"></div>
        <div class="tab  show">
            Customers
        </div>
        <div class="tab ">
            <div id="driver-list" class="driver-list overflow-auto" >

            </div>
        </div>
        <div class="tab ">
           <div  id="vehicle-list" class="vehicle-list overflow-auto">

           </div>
        </div>
        <div class="tab">
            Depost
        </div>
        <div class="tab" id="route-list-tab-btn" >
            <div id="route-list" class="route-list overflow-auto" style="height: 400px !important;"></div>
            <div id="route-points-list" class="route-points-list overflow-auto" style="height: 400px !important;"></div>
        </div>
        <div class="tab ">
            Notes
        </div>
    </div>

</div>
<div id="map" class="map"></div>
<div  class="side-bar-menu" style="display: none">

</div>

<div  class="side-bar-driver-menu">
    <span onclick="Driver.getInstance().render()">Show Driver</span>
    <span onclick="Driver.getInstance().hide()">Hide Driver</span>
    <span onclick="Router.getInstance().add()">Add Router</span>
    <span id="show-routes" data-status="Hide">Show Routers</span>
    <span id="update-driver" data-status="Hide">Update Driver</span>
    <span id="router-history" data-status="Hide">Router History</span>
  <!--  <span id="territory-list" data-status="Hide">Territory List</span>-->
    <span id="show-schedule-time" data-status="Hide">Show Schedule</span>
    <span id="territory-manage" data-status="Hide">Territory Manage</span>
</div>
<div  class="un-assign-warning">
     UnAssign Points <span class="">0</span>
</div>
<div  class="delay-warning">
    Delay Points <span class="">0</span>
</div>

<script   src="https://maps.googleapis.com/maps/api/js?key={{:config('GOOGLE_MAP_API_KEY')}}&callback=initMap&libraries=geometry"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<script src="__STATIC__/static/js/Sortable.js?v={{:config('STATIC_VERSION')}}"></script>
<script src="__STATIC__/static/js/table-drap-sort.js?v={{:config('STATIC_VERSION')}}"></script>
<script>
    Handlebars.registerHelper("drawRouterIcon",function(value){
            return `<span style="background: ${value};width: 18px;height: 18px;display: block;"></span>`;
    });
    Handlebars.registerHelper("getIndex",function(value){
        return  value + 1;
    });
    Handlebars.registerHelper("getDelayStyle",function(value){
        if(value.delay){
            return `color:red`;
        }
    });
    Handlebars.registerHelper("isExcetion",function(value){
        if(OBJECT.exceptionRouter.has( value ))
        {
            return `color:red;`
        }
        return '';
    });

    Handlebars.registerHelper("formateJsonToString",function(data){
          return JSON.stringify(data)
    });
    Handlebars.registerHelper("getSelectMonth",function(index){
         if(index==0){
             return 'selected';
         }
    });

    Handlebars.registerHelper("getDriverDepartureInfo",function( data ){
        let routerId = CONFIG.currentOpearateRouterId;
        let driverId = OBJECT.routerPonits[routerId].driverId;
        let driver = null;
        OBJECT.driverList.forEach( function ( value ,index ) {
               if( value.driver_id == driverId )
               {
                   driver = value;
               }
        });
        return `  <tr >
                      <th colspan="9" style="font-weight: bold;">
                      &nbsp;&nbsp;&nbsp;&nbsp;Lacation :${CONFIG.wareHouseCenter.address}
                      <br/>
                      &nbsp;&nbsp;&nbsp;&nbsp;WorkHour:${driver.work_hours}h &nbsp;&nbsp;&nbsp;&nbsp; End Location:${driver.end_location}&nbsp;&nbsp;&nbsp;&nbsp;DepartrueTime :${driver.departure_time}
                      </th>
                 </tr>`
    });



</script>
<!--territory-manage template-->

<!--路由列表模板-->

<script type="text/template" id="route-list-template">

    <table class="bootsrtop-table" id="route-list-table" style="width: 700px;">
        <thead>
        <tr>
            <th></th>
            <th></th>
            <th>Name</th>
            <th>Drivers</th>
            <th>Vehicles</th>
            <th>Stops</th>
            <th>Distance</th>
            <th>Hours</th>
            <th>lbs(Total)</th>
        </tr>
        </thead>
        <tbody>
        {{#each data}}
        <tr  class="showRoutePoints" data-router="{{routerId}}" data-driver="{{driver}}" style="{{isExcetion routerId}}">
            <th>
                <a href="javascript:;" style="text-decoration: none;font-size: 26px;" class="deleteRouter" title="Delete" data-router="{{routerId}}">-</a>
            </th>
            <th >{{{drawRouterIcon routerBg}}}</th>
            <th >{{{name}}}</th>
            <td>{{driver}}</td>
            <td>{{vehicleId}}</td>
            <td>{{stops}}</td>
            <td>{{distance}}(英里)</td>
            <td>{{time}}(h)</td>
            <td>{{lbs}}</td>
        </tr>
        {{/each}}
        </tbody>
    </table>

</script>
<script type="text/template" id="set-route-list-template">

    <table class="bootsrtop-table" >
        <thead>
        <tr>
            <th></th>
            <th>Name</th>
            <th>Drivers</th>
            <th>Vehicles</th>
            <th>Stops</th>
            <th>Distance</th>
            <th>Hours</th>
            <th>lbs(Total)</th>
            <td>Opreate</td>
        </tr>
        </thead>
        <tbody>
        {{#each data}}
        <tr>
            <th >{{{drawRouterIcon routerBg}}}</th>
            <th >{{{name}}}</th>
            <td>{{driver}}</td>
            <td>{{vehicleId}}</td>
            <td>{{stops}}</td>
            <td>{{distance}}(英里)</td>
            <td>{{time}}(h)</td>
            <td>{{lbs}}</td>
            <td >
                <a
                   href="javascript:;"
                   onclick="addRouterForDriver('{{../driver_id}}','{{routerId}}','{{driver}}')"
                   data-assignStatus="{{driver}}"
                   title="Add Router"
                   style="text-decoration: none;font-size: 12px;"
                >+</a>&nbsp;
                &nbsp;
                <a
                    href="javascript:;"
                    onclick="unAssignRouterForDriver('{{routerId}}')"
                    data-assignStatus="{{driver}}"
                    title="Unassing Router"
                    style="text-decoration: none;font-size: 12px;"
            >-</a></td>
        </tr>
        {{/each}}
        </tbody>
    </table>

</script>
<script type="text/template" id="route-points-list-template">
    <h2>{{driver}}</h2>
    <table class="bootsrtop-table " id="table-sort" style="width: 1000px;" >
        <thead class="nobg">
        <tr>
        <th>NO</th>
        <th width="100px">Schedule</th>
        <th>ScheduleTime</th>
        <th>Minute</th>
        <th>Arrive Time</th>
        <th>lbs</th>
        <th>Distance</th>
        <th>Location</th>
        <th>Address</th>

    </tr>
    </thead>
    <tbody id="route-points-list-body">
    {{{getDriverDepartureInfo @this}}}

    {{#each data}}
    <tr data-key="{{@index}}" id="row_{{getIndex @index}}" class="route-points-info" style="{{getDelayStyle this}}">
        <td>{{getIndex @index}}</td>
        <td>{{ScheduleID}}</td>
        <td>{{ScheduleTime}}</td>
        <td>{{minute}}</td>
        <td>{{arriveTime}}</td>
        <td>{{lbs}}</td>
        <td>{{distance}}</td>
        <td>{{CustomerTag}}</td>
        <td>{{Address}}</td>
    </tr>
    {{/each}}

    </tbody>
    </table>
</script>

<script type="text/template" id="date-pickr">
        <div class="date-pickr">
            <div class="ago-month">
                {{#each month}}
                <span class="{{getSelectMonth @index}} ago-month-items" data-month="{{month}}" data-year="{{year}}" >{{text}}</span>
                {{/each}}
            </div>
            <div class="ago-month-days">
                {{#each day}}
                <span class="ago-days" data-day="{{text}}">{{text}}</span>
                {{/each}}
            </div>
        </div>

</script>
<!--territory-list-->
<script type="text/template" id="territory-list-template">
    <ul class="territory-list">
        {{#each data}}
        <li data-points='{{formateJsonToString points}}' data-title="{{title}}">{{day}}&nbsp;&nbsp;{{warehouse}}&nbsp;&nbsp;{{title}}</li>
        {{/each}}
    </ul>
</script>
<script type="text/template" id="driver-list-template">
    <select name="driver-filter" id="driver-filter" class="driver-filter" onchange="showDriverList(this.value)">
        <option value="all" >All</option>
        <option value="unAssign">unAssign</option>
    </select>
    <table class="bootsrtop-table driver-list-table" style="width: 700px !important;">
        <thead class="nobg">
        <tr>
            <th width="90">Driver Id</th>
            <th width="120px">Vehicle Id</th>
            <th width="120px">NickName</th>
            <th width="120px">Start Location</th>
            <th width="120px">End Location</th>
            <th width="250px;">Address</th>
        </tr>
        </thead>
        <tbody id="driver-list-table-body">
        {{#each data}}
        <tr onclick="setRoute('{{driver_id}}')">
            <td>{{driver_id}}</td>
            <td>{{vehicle_id}}</td>
            <td>{{nickname}}</td>
            <td>{{start_location}}</td>
            <td>{{end_location}}</td>
            <td>{{address}}</td>
        </tr>
        {{/each}}
        </tbody>
    </table>
</script>
<script type="text/template" id="vehicle-list-template">
    <table class="bootsrtop-table" >
        <thead class="nobg">
        <tr>
            <th width="90">Vehicle Id</th>
            <th width="90">Name</th>
            <th width="120px">Depot</th>
            <th width="120px">Max Stops</th>
        </tr>
        </thead>
        <tbody>
        {{#each data}}
        <tr>
            <td>{{vehicle_id}}</td>
            <td>{{name}}</td>
            <td>{{depot}}</td>
            <td>{{max_stops}}</td>
        </tr>
        {{/each}}
        </tbody>
    </table>
</script>


<script>

  /* function updateRouters() {
       var routerId =  $('#routerId').val();
       var data=[];
       var lis = $('#foo li');
       $.each(lis ,function (k,v) {
           data.push($(v).data('router'));
       });
       RecordAndRestoreObj.saveRecord( routerId , data);
       $.ajax({
           type: "POST",
           dataType: "json",
           url: CONFIG.updateRouterUrl ,
           data: {id:routerId,routers:JSON.stringify(data)},
           success: function (result) {},
           error : function() {
               alert('更新失败  ')
           }
       });
   }*/
   /*在左侧工作台显示司机数据*/
   function showDriverList (filter = 'all') {
       let source=$('#driver-list-template').html();
       let template = Handlebars.compile(source);
       let data=[];
       if( filter=='all' )
       {
           data = OBJECT.driverList;
           $('#driver-list').html(template({data:data}));
       }else{
           let assignedDriverId = Driver.getInstance().getAssignedDriver();
           //driver-list-table-body"
           let html='';
           OBJECT.driverList.forEach(function ( value ,index ) {
                 if( assignedDriverId.indexOf( value.driver_id) < 0 )
                 {
                     html+=` <tr onclick="setRoute('${value.driver_id}')">
                                <td>${value.driver_id}</td>
                                <td>${value.vehicle_id}</td>
                                <td>${value.nickname}</td>
                                <td>${value.start_location}</td>
                                <td>${value.end_location}</td>
                                <td>${value.address}</td>
                            </tr>`;
                     $('#driver-list-table-body').html(html)
                 }
           })
       }


   }
  /**
   *显示日期列表框
   */
  function showDatePickr (element , title , callback) {
      $(element).click( function () {
          let month = getAgoMonth(3);
          let source=$('#date-pickr').html();
          let day = getDays(month[0].year,month[0].month)
          let template = Handlebars.compile(source);
          let html = template({month:month,day:day});
          $.Pop(html,{Close:true,Title:title,Btn:{yes:{vla:"确定"}}});
          $(document).on('click','.ago-month-items',function () {
              $(this).siblings().removeClass('selected');
              $(this).addClass('selected');
              let month = $(this).data('month');
              let year = $(this).data('year');
              let days = getDays(year,month);
              let daysHtml='';
              for (let i=0;i<days.length;i++)
              {
                  daysHtml+=`<span class="ago-days" data-day="${days[i].text}">${days[i].text}</span>`
              }
              $('.ago-month-days').html( daysHtml);
              //<span class="ago-days" data-day="2018-4-02">2018-4-02</span>

          });
          callback();
      })

  }
  /**
   * 点击日期 生成对应的区域和司机数据
   */
  showDatePickr('#router-history','Territory History',function () {
      $(document).on('click','.ago-days',function () {
          let day = $(this).data('day');
          new Promise(function( resolve, reject){
              $.ajax({
                  type: "POST",
                  dataType: "json",
                  url: "{{:url('/router/getDayRouter')}}",
                  data: {day:day,warehouse:"{{$Think.get.wareHouse}}"},
                  success: function (result) {
                      if(result.code==200)
                      {
                          resolve(result.msg);
                      }else{
                          reject(result.msg)
                      }
                  }
              });
          }).then( function (value) {
              //设置Router数据来源
              CONFIG.routerDataFromDate = day;
              Territory.getInstance().createTerritory( value );
          },function (errror) {
              $.Pro(errror);
          })
      })
  });

  /**
   * 点击日期 生成对应的区域(没有司机数据）
   */
/*  showDatePickr('#territory-list','Territory List',function () {
      $(document).on('click','.ago-days',function () {

          let day = $(this).data('day');
          new Promise( function ( resolve , reject) {
              $.ajax({
                  type: "POST",
                  dataType: "json",
                  url: "{{:url('/router/getDayTerritory')}}" ,
                  data: {warehouse:"{{$Think.get.wareHouse}}",day:day},
                  success: function (result) {
                      result.code == 200 ? resolve(result.msg) : reject('No Data!');
                  },
                  error : function(error) {
                     reject('Server Error [:/router/getDayTerritory]')
                }
              });
          }).then(function (data) {
              data.forEach( function (value) {
                     let router_edge_points = value.router_edge_points;
                    let title = value.title;
                    let routerId = md5(new Date().toDateString()+Math.random());
                    //下面操作顺序不要弄反了
                    //设置Router对象基本参数
                    OBJECT.routerEdgePoints[routerId] = router_edge_points;
                    OBJECT.routerPonits[routerId]=[];
                    OBJECT.routerPonits[routerId].UpdateStatus = true;
                    OBJECT.routersNameMap[routerId] = title;
                    //把响应点放进区域
                    Server.getInstance().assignPointToPolygon();
                    //画多边形
                    Polygon.draw( router_edge_points, map ,routerId );
                });
          },function (error) {
               $.Pro(error);
          });


      })
  });*/
/*对客户客户有时间要求的显示Market*/
$('#show-schedule-time').click(function () {
       let status = $(this).data('status');
       if(status=='Hide')
       {
           Customer.getInstance().showScheduleTime();
           $(this).data('status','Show');
           $(this).text('Hide Schedule')
       }else{
           Customer.getInstance().hideScheduleTime();
           $(this).data('status','Hide');
           $(this).text('Show Schedule')
       }
});




   /**
    * 点击Territory List名称 生成对应的区域没有司机数据
    */
/*   $(document).on('click','.territory-list li',function () {
       let points = $(this).data('points');
       let title = $(this).data('title');
       let routerId = md5(new Date().toDateString()+Math.random());
       //一下操作顺序不要弄反了
       //设置Router对象基本参数
       OBJECT.routerEdgePoints[routerId] = points;
       OBJECT.routerPonits[routerId]=[];
       OBJECT.routerPonits[routerId].UpdateStatus = true;
       OBJECT.routersNameMap[routerId] = title;
       //把响应点放进区域
       Server.getInstance().assignPointToPolygon();
       //画多边形
       Polygon.draw( points, map ,routerId );
   });*/
   function renderVehicleList () {
       let source=$('#vehicle-list-template').html();
       let template = Handlebars.compile(source);
       let html = template({data:OBJECT.vehicleList});
       $('#vehicle-list').html(html)
      // $.Pop(html,{Close:true,Title:'设置路线',Btn:{yes:{vla:"确定"}}})
   }
   /**
    * 设置路线名称
    **/
   function setRouteName()
   {
       $.Pop(`<input id="routerName" value="No Title" style="width: 220px;height: 30px;padding-left: 10px;margin: 10px auto;display: block" onblur="CONFIG.addRouterNameTempValue=this.value">`,{Close:true,Title:'路线名称',Btn:{yes:{vla:"确定"}}})
   }

   /**
    * 司机设置路线
    * 
    */ 
   function setRoute(driver_id)
   {

       let html = getSetRouterHtml(driver_id);
       $.Pop(html,{Close:true,CloseBtn:true,Title:'设置路线',Btn:{yes:{vla:"确定"}}})
   }
   /***
    * 获取司机设置路线模板
    * */
   function getSetRouterHtml(driver_id)
   {
       let source=$('#set-route-list-template').html();
       let template = Handlebars.compile(source);
       let html = template({data:assignRoute.getInstance().getRouters(),driver_id:driver_id});
       return html;
   }
   /**
    * 增加Router
    **/
  function addRouterForDriver( driverId,routerId , assignStatus)
  {
      if(assignStatus!='UnAssign')
      {
          $.Pro('该路线已经分配');
          return false;
      }
      if(Router.getInstance().DriverIsAssign( driverId ))
      {
          $.Pro('该司机已经被分配路线了');
          return false;
      }

      let driverIsForbid = Customer.getInstance().driverIsForbid( OBJECT.routerPonits[routerId].points , driverId );
      if( driverIsForbid.isForbid === true )
      {
          $.Pro(`${driverIsForbid.driverName}司机已禁止`);
          return false;
      }
      OBJECT.routerPonits[routerId].driverId = driverId;
      OBJECT.routerPonits[routerId].vehicleId = getVehicleIdByDriverId( driverId );
      Server.getInstance().updateRouters();
      Router.getInstance().setRouterUpdateStatus( routerId , false);
      $.Pro('设置成功');
  }

  /**
   * 更新车辆数据
   */
  $('#update-driver').click( function () {
      new Promise(function (resolve,reject) {
          getDriverList(resolve);  //请求数据
      }).then(function () {
          showDriverList(); //刷新列表数据
          $.Pro('更新成功');
      })
  });
 /**
  *显示路线并且移除多边形
  */
    $('#show-routes').click(function () {
           let status = $(this).data('status');
           let routerId = CONFIG.currentOpearateRouterId;
           if( !routerId )
           {
               $.Pro('请选择一个Territory!');
               return false;
           }
        if( status=='Hide')
        {
            //移除多边形
            Polygon.removeAllPloygon();
            //显示路线
           // OBJECT.directionsDisplay.forEach( function () { });
            OBJECT.directionsDisplay[routerId].setMap( map );
            Router.getInstance().showNumberMarkOnRouter(routerId);
            //隐藏客户标记
            Customer.getInstance().hide();
            $(this).text('Hide Routers');
            $(this).data('status','Show');
        }else{
            //显示多边形
            Polygon.showAllPloygon()
            //隐藏路线
            OBJECT.directionsDisplay[routerId].setMap( null )
            Router.getInstance().hideMarkerOnRouter( routerId );
            //显示客户标记
            Customer.getInstance().show();
            $(this).text('Show Routers');
            $(this).data('status','Hide');
        }

    })

  //Delete Router
   $(document).on('click','.deleteRouter',function (e) {
       let routerId = $(this).data('router');
       Router.getInstance().removeRouter( routerId );
       Polygon.removePloygonFromMap( routerId );
       $.Pro('移除成功');
       deleteRouterFromService(routerId);
       e.stopPropagation();
   });
     /**
      *从服务器数据库中删除一条Router信息
      */
    function deleteRouterFromService (routerId) {
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "{{:url('/router/delete')}}",
            data: {id:routerId},
            success: function (result) {}
        });
    }
  //show RouterPoints
   $(document).on('click','.showRoutePoints',function (e) {
       showLoading();
       let routerId = $(this).data('router');
       let driver = $(this).data('driver');
       setTimeout(()=>{
           assignRoute.getInstance().showRoutePoints(routerId,driver);
       },CONFIG.updateRouterPointsTimeInterval)




   });
    /**
     *通过司机id查找车辆id
     */
  function getVehicleIdByDriverId( driverId )
  {
      for( let id in OBJECT.driverList)
      {
          if(OBJECT.driverList[id].driver_id == driverId )
          {
              return OBJECT.driverList[id].vehicle_id;
          }
      }
      return null;
  }
 /**
  *取消分配司机
  **/
  function unAssignRouterForDriver(routerId)
  {
          OBJECT.routerPonits[routerId].vehicleId = null;
          OBJECT.routerPonits[routerId].driverId = null;
          Router.getInstance().setRouterUpdateStatus( routerId , false);
          $.Pro('取消成功');

  }

  /*展开和收起左侧工作台*/
  $('.open-show-btn').click(function () {
       if($(this).hasClass('open')){
            $(this).addClass('colse').removeClass('open');
            $('.work-area').animate({width:"0px"},500);
            $('#map').animate({width:"100%"},500);
       }else{
           let wWid = $(window).width();
           let mapWid = wWid - 500;
           $(this).addClass('open').removeClass('colse');
           $('.work-area').animate({width:"500px"},500);
           $('#map').animate({width:`${mapWid}px`},500);
       }
  });

   /**
    * 未排站遗漏的站点
    *  1 统计OBJECT.customerPositionList 长度 as total
    *  2 计算每个多边形的客户数量               as EveryCount
    *  3 UnCheckPoints = total -( sum(EveryCount) )
    */
   function  checkUnAssignPonits() {
       let total = OBJECT.customerPositionList.length;
       let count = 0;
       for( let index in OBJECT.routerPonits )
       {
           if(OBJECT.routerPonits[index].points)
           {
               count = count + OBJECT.routerPonits[index].points.length;
           }
       }
       let UnCheckDropPonitsNum = total - count;
       if( UnCheckDropPonitsNum > 0 )
       {
           let html=` UnAssign Points <span class="warning">${UnCheckDropPonitsNum}</span>`;
           $('.un-assign-warning').html(html);
       }else{
           let html=` UnAssign Points <span>0</span>`;
           $('.un-assign-warning').html(html);

       }
       setTimeout('checkUnAssignPonits()',CONFIG.checkUnAssignTimeInterval);
   }
   setTimeout('checkUnAssignPonits()',CONFIG.checkUnAssignTimeInterval);
   /**
    * 检查迟到站点
    */
   function  checkDelayPoints() {
       assignRoute.getInstance().countDelayPoints();
       let  delayPointsCounter = CONFIG.delayPointsCounter;
       if( delayPointsCounter  )
       {
           let html=`Delay Points <span class="warning">${delayPointsCounter}</span>`;
           $('.delay-warning').html(html);
       }else{
           let html=` Delay Points <span class="">${delayPointsCounter}</span>`;
           $('.delay-warning').html(html);
       }
       setTimeout('checkDelayPoints()',CONFIG.checkUnAssignTimeInterval);
   }
   checkDelayPoints();

   /**
    *
    * @param unAssignPointNums
    */
   function updateUnAssignPoints ( unAssignPointNums )
   {
       if( unAssignPointNums > 0 )
       {
          let html=`有${unAssignPointNums}订单未处理</span>`;
           $('.un-assign-warning').html(html);
           setTimeout('checkUnAssignPoints()',CONFIG.checkUnAssignTimeInterval);
       }
   }
  // setTimeout('checkUnAssignPoints()',CONFIG.checkUnAssignTimeInterval);
/*捕获全局异常*/
   window.addEventListener("error", function (e) {

       colseLoading();
       try{
           $.ajax({
               type: "POST",
               dataType: "json",
               url: '{{:url("/log/debug")}}' ,
               data: {message:e.error.message,filename:e.filename,lineno:e.lineno},
               success: function (result) {}
           });
       }catch (e)
       {

       }

       return false;
   })
  $(function () {
     colseLoading();
  });




</script>

<!--引入文件区域-->
{include file="router/territory-manage" /}
</body>
</html>